package com.android.equipment.dao.operate;

import com.android.equipment.ObjectBox;
import com.android.equipment.dao.User;
import com.android.equipment.dao.User_;
import com.blankj.utilcode.util.SPUtils;

import java.util.List;

import io.objectbox.Box;
import io.objectbox.query.Query;

public class DaoUser {
    static Box<User> userBox;
    private static DaoUser instance;
    private DaoUser(){}

    public static DaoUser getInstance() {
        if (instance == null) {
            instance = new DaoUser();
            userBox = ObjectBox.get().boxFor(User.class);
        }
        return instance;
    }

    public boolean checkIsFirstLogin(){
        Query<User> query = userBox.query().build();
        List<User> users = query.find();
        query.close();
        return users.isEmpty();
    }

    public void initSaveUser(){
        Query<User> query = userBox.query().build();
        List<User> users = query.find();
        query.close();
        if (users.size() <= 0){
            User adminUser = new User();
            adminUser.setAccount("admin");
            adminUser.setPassword("123456");
            userBox.put(adminUser);

            User superAdminUser = new User();
            superAdminUser.setAccount("superAdmin");
            superAdminUser.setPassword("123456");
            userBox.put(superAdminUser);
        }
    }

    public boolean checkUserLogin(String account, String password){
        Query<User> query = userBox.query(User_.account.equal(account)).build();
        User user = query.findUnique();
        query.close();
        if (null != user){
            if (user.getPassword().equals(password)){
                SPUtils.getInstance().put("userId",user.getId());
                return true;
            }else {
                return false;
            }
        }
        return false;
    }

    public String getUserAccount(){
        Long userId = SPUtils.getInstance().getLong("userId");
        Query<User> query = userBox.query(User_.id.equal(userId)).build();
        User user = query.findUnique();
        if (null != user){
            return user.getAccount();
        }else {
            return "";
        }
    }
    public boolean updateUserPass(String pass){
        Long userId = SPUtils.getInstance().getLong("userId");
        Query<User> query = userBox.query(User_.id.equal(userId)).build();
        User user = query.findUnique();
        if (null != user){
            user.setPassword(pass);
            userBox.put(user);
            return true;
        }else {
            return false;
        }

    }

    public String getUserPassWord() {
        Long userId = SPUtils.getInstance().getLong("userId");
        Query<User> query = userBox.query(User_.id.equal(userId)).build();
        User user = query.findUnique();
        if (null != user){
            return user.getPassword();
        }else {
            return "";
        }
    }
}
